package org.kiwi.data.preheat;

import org.kiwi.data.util.DataSourceUtil;
import org.kiwi.preheat.spi.PreheatProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;

/**
 * Created by jack on 16/12/31.
 */
public class DatabasePreheatProvider extends PreheatProvider {

    private static final Logger LOGGER = LoggerFactory.getLogger(DatabasePreheatProvider.class);

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void doPreheat() {
        Map<String, DataSource> dataSources = applicationContext.getBeansOfType(DataSource.class);
        if (dataSources != null && dataSources.size() > 0) {
            for (Map.Entry<String, DataSource> entry : dataSources.entrySet()) {
                try {
                    for (int i = 0; i < 10; i++) {
                        DataSourceUtil.doHeartBeat(entry.getValue());
                    }
                } catch (SQLException e) {
                    LOGGER.warn(">>>>> datasource [{}] preheat error :[{}]", entry.getKey(), e.getMessage());
                }
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(">>>>> datasource [{}] was preheated.", entry.getKey());
                }
            }
        }
    }

}
